<template>
  <div class="bundles"
       v-loading="loading">
    <div class="bundles-info">{{$t('billing.youBundles')}}</div>
    <div class="bundles-type">{{ bundlesObj.status }}</div>
    <div class="bundles-info"
         style="height: 28px"><span v-if="bundlesObj.status !== 'Free'">${{amount}} {{$t('billing.info')}} {{ bundlesObj.nextTime }}</span>&nbsp;</div>
    <div class="bundles-btn" v-if="$hasPermission('sys:billing:action')">
      <template v-if="bundlesObj.status === 'Free'|| bundlesObj.status === alaCarteStr">
        <el-button size="medium"
                   v-if="dataFrom !== 'tenant'"
                   type="primary"
                   @click="jump">{{$t('billing.upgrade')}}</el-button>
        <el-button size="medium"
                   class="marginTop"
                   v-if="dataFrom !== 'tenant' && bundlesObj.status === alaCarteStr && bundlesObj.payStatus"
                   type="text"
                   @click="addUserVisible = true">Add more users</el-button>
        <el-button size="medium"
                   type="info"
                   class="marginTop"
                   v-if="dataFrom !== 'tenant' && bundlesObj.status === alaCarteStr && !bundlesObj.payStatus"
                   @click="activationSubscription">{{$t('renew')}}</el-button>
      </template>
      <template v-else-if="bundlesObj.status === 'Startup'">
        <el-button size="medium"
                   type="primary"
                   v-if="dataFrom !== 'tenant'"
                   @click="jump">{{$t('billing.upgrade')}}</el-button>
        <el-button size="medium"
                   class="marginTop"
                   v-if="bundlesObj.payStatus"
                   type="text"
                   @click="cancelSubscription">{{$t('cancel')}}</el-button>
        <el-button size="medium"
                   type="info"
                   class="marginTop"
                   v-if="!bundlesObj.payStatus"
                   @click="activationSubscription">{{$t('renew')}}</el-button>
      </template>
      <template v-else-if="bundlesObj.status === 'Professional'">
        <el-button size="medium"
                   type="primary"
                   v-if="dataFrom !== 'tenant'"
                   @click="jump">{{$t('billing.upgrade')}}</el-button>
        <el-button size="medium"
                   class="marginTop"
                   v-if="bundlesObj.payStatus"
                   type="text"
                   @click="cancelSubscription">{{$t('cancel')}}</el-button>
        <el-button size="medium"
                   type="info"
                   class="marginTop"
                   v-if="!bundlesObj.payStatus"
                   @click="activationSubscription">{{$t('renew')}}</el-button>
      </template>
      <template v-else>
        <el-button size="medium"
                   class="marginTop"
                   v-if="bundlesObj.payStatus"
                   type="text"
                   @click="cancelSubscription">{{$t('cancel')}}</el-button>
        <el-button size="medium"
                   type="info"
                   class="marginTop"
                   v-if="!bundlesObj.payStatus"
                   @click="activationSubscription">{{$t('renew')}}</el-button>
      </template>
    </div>
    <a-la-carte-more-user :visible.sync="addUserVisible" :aLaCarte="aLaCarte"></a-la-carte-more-user>
  </div>
</template>

<script>
// import { getCharge } from '@/components/storybook/utilties/chargebee'
import monent from 'moment'
import { stringRemoveSpaceEqual } from '@/utils'
import config from '@/utils/config'
import aLaCarteMoreUser from './aLaCarteMoreUser'

export default {
  name: 'bundles',
  components: {
    aLaCarteMoreUser
  },
  props: ['youBundles', 'aLaCarte', 'dataFrom'],
  inject: {
    _tenantCode: {
      default: () => {
        return function () {}
      }
    }
  },
  data () {
    return {
      loading: true,
      amount: 0,
      alaCarteStr: config.alaCarteString,
      addUserVisible: false
    }
  },
  computed: {
    tenantCode () {
      return this._tenantCode()
    },
    bundlesObj () {
      let obj = {}
      if (this.youBundles) {
        obj.payStatus = this.youBundles.payStatus
        obj.status = stringRemoveSpaceEqual(this.youBundles.name, config.alaCarteString) ? config.alaCarteString : this._.capitalize(this.youBundles.name)
        obj.nextTime = monent(this.youBundles.nextBilling).format('MMM DD YYYY')
        this.getNextBillingAmount()
      } else {
        obj.status = 'Free'
      }
      return obj
    }
  },
  watch: {
    youBundles (val) {
      this.loading = false
    }
  },
  methods: {
    async cancelSubscription (row) {
      if (this.dataFrom === 'tenant') {
        this.$msgbox({
          title: this.$t('prompt.title'),
          message: this.$t('billing.cancelTip'),
          confirmButtonText: this.$t('billing.cancelNow'),
          cancelButtonText: this.$t('billing.dismiss'),
          showCancelButton: true,
          type: 'warning'
        }).then(async () => {
          const { cancelSubscription } = this.$interface.pay
          try {
            const { data } = await cancelSubscription({ subscriptionId: this.youBundles.subscriptionId })
            if (data.code !== 0) {
              this.$message.error(data.msg)
            } else {
              this.loading = true
              this.$message.success(this.$t('billing.cancelSuccess'))
              this.$emit('changeBundles')
            }
          } catch (e) {
            console.log(e)
          }
        }).catch(() => { })
      } else {
        const url = this.$router.resolve({ name: 'feedback', query: { FormTitle: 'Cancel Subscription', RoleEamil: this.$store.state.user.email, tenantCode: this.$store.state.user.tenantCode } })
        window.open(url.href, '_blank')
      }
    },
    async activationSubscription (row) {
      this.$msgbox({
        title: this.$t('prompt.title'),
        message: this.$t('billing.renewTip'),
        confirmButtonText: this.$t('billing.renewNow'),
        cancelButtonText: this.$t('billing.dismiss'),
        showCancelButton: true,
        type: 'warning'
      }).then(async () => {
        const { activationSubscription } = this.$interface.pay
        try {
          const { data } = await activationSubscription({ subscriptionId: this.youBundles.subscriptionId, reactivateFrom: monent(this.youBundles.cancelledAt).valueOf() })
          if (data.code !== 0) {
            this.$message.error(data.msg)
          } else {
            this.loading = true
            this.$message.success(this.$t('billing.renewSuccess'))
            this.$emit('changeBundles')
          }
        } catch (e) {
          console.log(e)
        }
      }).catch(() => { })
    },
    jump () {
      this.$router.push({ path: '/paywallBuy' })
    },
    async getNextBillingAmount () {
      try {
        const tenantCode = this.tenantCode || this.$store.state.user.tenantCode
        const { nextBillingAmount } = this.$interface.pay
        const { data } = await nextBillingAmount({ tenantCode })
        this.amount = data.code === 0 ? Object.values(data.data).reduce((x, y) => x + y, 0) / 100 : 0
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    }
  },
  created () {
    // this.getData()
  }
}
</script>

<style scoped lang="scss">
.bundles {
  width: 268px;
  background: #f2f4f8;
  padding: 12px;
  box-shadow: 0 0 2px #00000033, 0 2px 10px #00000019;
  border-radius: 4px 4px 4px 4px;
  &-info {
    font-size: 12px;
    color: #8d8d8d;
    line-height: 14px;
  }
  &-type {
    margin: 8px 0;
    font-weight: bold;
    color: #0043ce;
    line-height: 24px;
    font-size: 20px;
  }
  &-btn {
    margin-top: 16px;
    position: relative;
    height: 80px;
  }
  .marginTop {
    position: absolute;
    top: 44px;
    left: 0;
    right: 0;
  }
  .el-button {
    width: 100%;
    margin: 0;
  }
}
</style>
